<?php

namespace App\Admin\Forms;

use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\EasyExcel\Excel;
use Illuminate\Support\Facades\DB;

class ImportCouponExcel extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         if (!isset($input['codes_excel'])
             || !isset($this->payload['id'])
            || !$allSheets = Excel::import(config('filesystems.disks.admin.root'). '/' .$input['codes_excel'])
         ) {
             return $this->response()->error('缺失参数');
         }

         $content = $allSheets->toArray();
         $data = [];
         foreach ($content as $sheets) {
             // 第一层 循环 sheet
             foreach ($sheets as $row) {
                 $data[] = [
                     'validity_time'    =>  3 * 24 * 3600,
                     'coupon_type_id'   =>  $this->payload['id'],
                     'exchange_end_time'    =>  Carbon::parse('+3 months')->toDateTimeString(),
                     'card_nums'            =>  $row['卡号'],
                     'card_secret'          =>  $row['卡密']
                 ];
             }
         }

         if ($data && DB::table('coupon_codes')->insert($data)) {
             return $this
                 ->response()
                 ->success('导入成功')
                 ->refresh();
         }

         return $this->response()->error('操作异常');
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->file('codes_excel')->accept('xlsx')->autoUpload();
    }

}
